--[[
模块名称：chg
模块功能：充电模块处理函数
模块最后修改时间：2017.08.25
]]

require"sys"
module(...,package.seeall)

local inf = {}

--[[
函数名：proc
功能  ：充电消息处理
参数  ：上报消息
返回值：无
]]
local function proc(msg)
	if msg then	
		if msg.level == 255 then return end	
		inf.vol = msg.voltage		
		inf.lev = msg.level
		local flag = (islowvolt() and getstate() ~= 1)
		if inf.low ~= flag then
			if (inf.low and (getstate()==1)) or flag then
				inf.low = flag
				sys.publish("DEV_CHG_IND","BAT_LOW",flag)
			end
		end		
		
		local flag = (islow1volt() and getstate() ~= 1)
		if inf.low1 ~= flag then
			if (inf.low1 and (getstate()==1)) or flag then
				inf.low1 = flag
				sys.publish("DEV_CHG_IND","BAT_LOW1",flag)
			end
		end	
		
		if inf.lev == 0 and not inf.chg then
			if not inf.poweroffing then
				inf.poweroffing = true
				sys.timerStart(rtos.poweroff,30000,"chg")
			end
		elseif inf.poweroffing then
			sys.timerStop(rtos.poweroff,"chg")
			inf.poweroffing = false
		end
		print("--zbb--chg proc",inf.chg,inf.lev,inf.vol,inf.state)
		sys.publish("DEV_VOLT_IND",inf.vol)
	end
end

--[[
函数名：init
功能  ：初始化
参数  ：无
返回值：无
]]
local function init()
	inf.vol = 0
	inf.lev = 0
	inf.chg = false
	inf.state = false
	inf.poweroffing = false
	inf.lowvol = 3600
	inf.low = false
	inf.low1vol = _G.LOWVOLT_FLY
	inf.low1 = false	
end

local charg
function getcharger()
    print("--zbb--getcharger",charg,pincfg.CHARGER())
    if charg ~=  pincfg.CHARGER() then
        charg = pincfg.CHARGER()
        sys.publish("DEV_CHG_IND","CHARGER",charg)
    end    
	return pincfg.CHARGER()==1 and true or false
end

function getvolt()
	return inf.vol
end

function getlev()
	if inf.lev == 255 then inf.lev = 95 end
	return inf.lev
end

function getstate()
	return inf.state
end

function islow()
	return false --inf.low
end

function islow1()
	return false --inf.low1
end

function islowvolt()
	return inf.vol<=inf.lowvol
end

function islow1volt()
	return inf.vol<=inf.low1vol
end

function stateind(intid)
	print("state ind",inf.state,intid)
	if intid == cpu.INT_GPIO_NEGEDGE then	--下降沿
		inf.state = true
	elseif intid == cpu.INT_GPIO_POSEDGE then	--上升沿
		inf.state = false
	elseif intid == nil then
		if pincfg.CHG_STATUS() == 0 then
			inf.state = true	
		elseif pincfg.CHG_STATUS() == 1 then
			inf.state = false	
		end
	end
	sys.publish("DEV_CHG_IND","CHG_STATUS",getstate())
end

--注册消息的处理函数
rtos.on(rtos.MSG_PMD,proc)
init()
sys.timerLoopStart(getcharger,5000)
nvm.init("config.lua")
